<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\11\10 0010
 * Time: 16:44
 */
namespace models;
class Base64Image
{

    /**
     * 保存用户上传的图片
     * @param string $key form表单的字段
     * @param string $path 保存的路径
     * @return bool|string
     */
    public function move_image($key, $path){
        header('Content-type:text/html;charset=utf-8');
        $imgdata = $_POST[$key];
        if(!file_exists($path)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($path, 0700);
        }
        $result = $this->base64_image_content($imgdata,$path);
        return $result;
    }

    /**
     * 把base64数据转存为图片并保存
     * @param string $base64_image_content base64图片
     * @param string $path 保存路径
     * @return bool|string
     */
    public function base64_image_content($base64_image_content,$path){
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $base64_string= explode(',', $base64_image_content);
            $result[1] = str_replace(' ','+',$base64_string['1']);
            $new_file = $path."/".date('Ym',time())."/";
            $basePutUrl = $new_file;
            if(!file_exists($basePutUrl)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($basePutUrl, 0700);
            }
            $ping_url = mt_rand(10000000,99999999).time().".{$type}";
            $ftp_image_upload_url = $new_file.$ping_url;
            $local_file_url = $basePutUrl.$ping_url;
            if (file_put_contents($local_file_url, base64_decode($result[1]))){
                //TODO 个人业务的FTP 账号图片上传
                //ftp_upload(C('REMOTE_ROOT').$ftp_image_upload_url,$local_file_url);
                if( !isset(Yii::app()->session['uploadImages']) && !is_array(Yii::app()->session['uploadImages']) ){
                    $_images = array();
                }else{
                    $_images = Yii::app()->session['uploadImages'];
                }
                array_push($_images,$ftp_image_upload_url);
                Yii::app()->session['uploadImages'] = $_images;// 将用户上传的图片存在session中
                return $ftp_image_upload_url;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 清除用户上传未选择的图片
     * @param array $imgs 用户选择的图片
     * @return bool
     */
    public static function clearMisImage($imgs){
        $alluploadImages = Yii::app()->session['uploadImages'];
        if($alluploadImages && is_array($alluploadImages)){
            array_map(function ($v){
                unlink($v);
            },array_diff($alluploadImages,$imgs));
            unset(Yii::app()->session['uploadImages']);
            return true;
        }else{
            return false;
        }
    }
}